﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TalksLog.Abstraction.Services;
using TalksLog.Entities;
using TalksLog.Services;
using TalksLog.UI.Common;
using TalksLog.UI.Models.BindingModels;

namespace TalksLog.UI.Controllers
{
    public class AccountController : Controller
    {
        private AccountServiceBase _servcie;
        private IMapper _mapper;

        public AccountController(AccountServiceBase service, IMapper mapper)
        {
            _servcie = service;
            _mapper = mapper;
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public IActionResult DoRegister(RegisterAccountBM model)
        {
            if (!ModelState.IsValid)
            {
                return View("Register");
            }

            model.Email = model.Email.Trim();
            Account account = _mapper.Map<Account>(model);

            string errorMessage;

            var result = _servcie.Register(account, out errorMessage);
            if (!result)
            {
                ModelState.AddModelError("register_error", errorMessage);
                return View("Register");
            }

            return this.DoLogin(new LoginAccountBM { Email = model.Email, Password = model.Password }); // 自动登录
        }

        public IActionResult Login(string returnUrl = null)
        {
            ViewData["returnUrl"] = returnUrl;
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model">登录信息</param>
        /// <param name="returnUrl">登录后跳转到的URL，如为null，则跳转到主页</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DoLogin(LoginAccountBM model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return View("Login");
            }

            model.Email = model.Email.Trim();

            Account account = _servcie.Find(model.Email, model.Password);
            if (account == null)
            {
                ModelState.AddModelError("account_error", "电子邮箱或密码错误");
                return View("Login");
            }

            this.Login(account);

            if (!string.IsNullOrWhiteSpace(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }

        // 设置cookie
        private void Login(Account account)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, account.Id.ToString()),
                new Claim(ClaimTypes.Name, account.Name),
                new Claim(ClaimTypes.Email, account.Email),
                new Claim(ClaimTypes.Gender, account.Gender),
                new Claim(ClaimTypesExt.RegisterDate, account.CreateTime.ToString("yyyy-MM-dd")),
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }

        [Authorize]
        public IActionResult Logout()
        {
            HttpContext.SignOutAsync();
            return RedirectToAction("Login", "Account");
        }

        [Authorize]
        public IActionResult ShowMyInfo()
        {
            return View();
        }
    }
}